<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>

</body>
<script>

    function ajax(options = {}) {
        var { type = "get", url, data = "", async = true, dataType = "text", success } = options;

        if (typeof data == "object") {
            // 解析为参数数据队列
            var list = [];
            for (var key in data) {
                var val = data[key];
                list.push(`${key}=${val}`);
            }
            data = list.join("&");
        }

        var xhr = new XMLHttpRequest();

        if (type.toLowerCase() == "get") {
            xhr.open("get", data ? url + "?" + data : url, async);
            xhr.send();
        } else if (type.toLowerCase() == "post") {
            xhr.open("get", url, async);
            xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            xhr.send(data);
        }

        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4 && xhr.status == 200) {
                var result = xhr.responseText;
                if (dataType == "json") {
                    result = JSON.parse(result);
                }

                if (success && typeof success == "function") {
                    success(result);
                }

            }
        }

    }



</script>

</html>